package com.service.garbage.ningbo;

import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.service.bean.device.Vehicle;
import com.service.other.Logger;

/**
 * Http工具类
 * @author wt
 *
 */
public class HttpUtil {
	/**
	 * 取得HTTP结果
	 * @param url
	 * @return
	 */
	public static void doGetStr(Vehicle vehicle,String url) {
		try {
			Logger.debug(vehicle.device.deviceNo,vehicle.device.deviceNo+"开始发送称重数据 doGetStr");
			DefaultHttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);
			HttpResponse response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();		
			if(entity != null){
				String result = EntityUtils.toString(entity,"GBK");
				result = result.replaceAll("&lt;","<");
				result = result.replaceAll("&gt;",">");
				xmlElements(vehicle,result);
			}else{
				Logger.debug(vehicle.device.deviceNo,vehicle.device.deviceNo+"【新世纪】无返回数据");
			}
		} catch (Exception e) {
			Logger.err(e);
		}
	}
	
	private static void xmlElements(Vehicle vehicle,String xmlDoc) throws DocumentException, UnsupportedEncodingException {
		Document document  = DocumentHelper.parseText(xmlDoc);
		//拿到根节点
		Element root = document.getRootElement();
		String result = root.elementTextTrim("Result");
		String gpsno = vehicle.device.deviceNo;
		if("1".equals(result)){
			Logger.debug(gpsno,gpsno+"返回值："+result+",数据传输成功!");
		}else if("0".equals(result)){
			Logger.debug(gpsno,gpsno+"返回值："+result+",数据传输失败");
		}else if("9".equals(result)){
			Logger.debug(gpsno,gpsno+"返回值："+result+",密钥不正确");
		}else{
			Logger.debug(gpsno,gpsno+"返回值："+result+",无返回值");
		}
	}
	
}
